import { PureComponent } from 'react'


export default class Message extends PureComponent{

  constructor(props) {
    super(props);
    this.state = {
      setEdit: false,
      editVal:props.message.message
    }
  }

  editText=null;
  componentDidUpdate(prevProps,prevState){
    if((!prevState.setEdit)
    && this.state.setEdit){
        // 让输入框获得焦点
      this.editText.focus();
    }
  }

  render() {
    const { message, delMessage ,changeDone,editMessage} = this.props
    const {setEdit,editVal} = this.state;
    return (
      <li className={ setEdit?'editing':'' }>
        <h3>{message.nickname}</h3>
        <input type="checkbox" 
          checked={message.done}
          onChange={({target})=>{
            changeDone(message.id,target.checked);
          }}/>
        <p onDoubleClick={() => {
          this.setState({
            setEdit:true
          });
        }}>
          {message.message}
        </p>
        <textarea 
          ref={(node)=>{
            this.editText = node;
          }}
          value={editVal}
          onChange={({ target }) => {
            this.setState({
              editVal:target.value
            })
          }}
          onBlur={()=>{
            if(editVal.trim()){
              editMessage(message.id,editVal); //如果编辑框的数据不为空，则修改
            } else {
              this.setState({
                editVal:message.message
              })
            }
            this.setState({
              setEdit:false
            })
          }}
        ></textarea>
        <div className="del-btn" onClick={() => {
            delMessage(message.id)
          }}>删除</div>
      </li>
    )
  }
}